class Contacts {

	/**
	 * 读取所有联系人
	 */
	async readContacts() {
		return new Promise((resolve, reject) => {
			uni.showLoading({
				mask:true,
				title:'正在加载...'
			})
			try {
				plus.contacts.getAddressBook(
					plus.contacts.ADDRESSBOOK_PHONE,
					function(addressbook) {
						addressbook.find(
							['displayName', 'phoneNumbers'],
							function(contacts) {
								if (contacts) {
									let phones = [];
									for (let c of contacts) {
										let numbs = c.phoneNumbers;
										let ps = [];
										for (let n of numbs) {
											ps.push(n.value);
										}
										phones.push({
											name: c.displayName,
											phones: ps
										});
									}
									uni.hideLoading()
									resolve(phones);
								} else {
									uni.hideLoading()
									resolve(null);
								}
							},
							function() {
								uni.hideLoading()
								resolve(null);
							}, {
								multiple: true
							}
						);
					},
					function(e) {
						uni.hideLoading()
						resolve(null);
					}
				);
			} catch (e) {
				uni.hideLoading()
				resolve(null);
			}
		});
	}
	
		async needAuthorize() {
			// #ifdef APP-PLUS
			const platform = uni.getSystemInfoSync().platform;
		
			if (platform === 'android') {
				// 安卓授权
				return await new Promise((resolve, reject) => {
					plus.android.requestPermissions(['android.permission.READ_CONTACTS'], function(e) {
						
						if (e.deniedPresent.length > 0) {
							//单次拒绝
							resolve(false);						
							return;
						}
						if (e.deniedAlways.length > 0) {
						// 	//永久拒绝
						console.log('权限被拒绝1');//这里处理安卓用户拒绝授权
						// 	uni.showModal({
						// 		title: '权限被拒绝',
						// 		content: '请在系统设置-应用管理-中开启通讯录权限',
						// 		showCancel: false,
						// 		success: () => resolve(false)
						// 	});
						} else {
							resolve(true);
						}
					}, () => resolve(false));
				});
			} else {
				// iOS 判断是否授权
				const granted = plus.contacts.getAddressBook(); // 试图获取通讯录，若没权限会失败
				
				setTimeout(()=>{
					let ios_contacts = uni.getStorageSync('get_contacts');
					if (!granted && !ios_contacts) {
						console.log('权限被拒绝2');//这里处理IOS用户拒绝授权
						// uni.showModal({
						// 	title: '权限被拒绝',
						// 	content: '请前往“设置-隐私-通讯录”中开启权限',
						// 	showCancel: false,
						// 	success: () => {}
						// });
						return false;
					}
				},3000);
	
				return true;
			}
			// #endif
		}
	
	}


	


export default Contacts;